const router = require('koa-router')();
const { models, Sequelize, sequelize } = require('../../utils/db');
const { resBody, randomArray } = require('../../utils/index')
const { Op, literal, col} = Sequelize;

// 获取是否登陆
function loginState(ctx) {
  if (ctx.session.userInfo) {
    return ctx.session.userInfo;
  }
  return false;
}

async function thumbsUpList(ctx) {
  // 登陆情况下返回点赞数据
  let userInfo = loginState(ctx);
  let thumbsUp = [];
  if (userInfo.users_id) {
    thumbsUp = await models.zan_model.findAll({
      raw: true,
      where: {
        user_id: userInfo.users_id,
        status: 1
      },
      attributes: ['type_id', 'type']
    });
  }
  return thumbsUp;
}

async function collectList(ctx) {
  // 登陆情况下返回点赞数据
  let userInfo = loginState(ctx);
  let collect = [];
  if (userInfo.users_id) {
    collect = await models.collect_model.findAll({
      raw: true,
      where: {
        user_id: userInfo.users_id,
        status: 1
      },
      attributes: ['sentence_id']
    });
  }
  return collect;
}

// 获取句子评论列表
async function getCommentList(sentenceId) {
  let commentList = await models.comment_model.findAndCountAll({
    // raw: true,
    order: [['id', 'DESC']],
    where: {
      compose_id: sentenceId
    },
    include: [
      {
        model: models.users_model,
        as: 'userInfo',
        attributes: ['users_id', 'nickname', 'head_pic']
      },
      {
        model: models.reply_model,
        as: 'reply',
        attributes: ['id', 'compose_id', 'compose_type', 'comment_id', 'content', 'praise', 'form_uid', 'to_uid', 'create_time'],
        include: [
          {
            model: models.users_model,
            as: 'userInfo',
            attributes: ['users_id', 'nickname', 'head_pic']
          },
          {
            model: models.users_model,
            as: 'toUserInfo',
            attributes: ['users_id', 'nickname', 'head_pic']
          }
        ]
      }
    ],
    attributes: ['id', 'compose_id', 'content', 'praise', 'from_userid', 'create_time']
  });
  // count 个数
  // rows 数据
  return commentList;
}

router.post('/getSentence', async(ctx) => {
    let { 
      pn = 1,
      ps = 10,
      id,
      categoryId,
      content,
      order
    } = ctx.request.body;
    let [ condition, count, data ] = [{}, 0, []];
    switch (order) {
      case 'rand':
        order = [[literal('RAND()')]];
        break;
      case 'asc':
        order = [['id', 'ASC']];
        break;
      case 'desc':
        order = [['id', 'DESC']];
        break;
      default:
        order = [['id', 'ASC']];
        break;
    }
    categoryId ? condition.categoryId = categoryId: '';
    id ? condition.id = id: '';
    content ? condition.content = {[Op.like]: `%${content}%`} : '';
    count = await models.sentence_model.count({where: condition});
    let indexSentenceList = randomArray(1, count, 200);
    condition.id = {
      [Op.in]: indexSentenceList
    };
    data = await models.sentence_model.findAll({
        raw: true,
        where: condition,
        order: order,
        attributes: ['id', col('special.sid'), col('special.title'), 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect'],
        limit: ps,
        offset: (pn - 1) * ps,
        include: [
          {
            model: models.special_model,
            as: 'special',
            attributes: []
          }
        ]
    });
    let thumbsUp = await thumbsUpList(ctx);
    let collect = await collectList(ctx);
    ctx.body = {
      ...resBody.success,
      data: {
        sentence: data,
        thumbsUp: thumbsUp,
        collect: collect
      }
    }
});
router.post('/getSpecialDetails', async(ctx) => {
    let { specialId } = ctx.request.body;
    specialId = Number(specialId)
    // 检索条件
    let condition = {};
    specialId ? condition.fromid = specialId: condition.fromid = 1;
    let {
      sid,
      title,
      categoryId,
      tagId
    } = await models.special_model.findOne({
      raw: true,
      where: {
        sid: specialId
      },
    });
    let data = await models.sentence_model.findAll({
        raw: true,
        where: condition,
        attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect']
    });
    ctx.body = { 
      ...resBody.success,
      data: {
        id: sid,
        title,
        list: data,
        category: categoryId,
        tagId: eval(tagId) || []
      }
    };
});
router.post('/getContent', async(ctx) => {
  let { id } = ctx.request.body;
  // 检索条件
  let condition = {
    id: id
  };
  let data = await models.sentence_model.findAll({
      raw: true,
      where: condition,
      attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect'],
  });
  let thumbsUp = await thumbsUpList(ctx);
  let collect = await collectList(ctx);
  ctx.body = { 
    ...resBody.success,
    data: {
      sentence: data.length >= 1 ? data[0]: {},
      thumbsUp,
      collect
    }
   };
});

router.post('/getSearchResult', async(ctx) => {
  let {
      keyword = '',
      type = '',
      pn = 1,
      ps = 10
    } = ctx.request.body;
  let data = [];
  let count = 0;
  let maxPage = 0;
  if (!keyword) {
    ctx.body = { data, count };
    return;
  }
  switch (type) {
    case 'sentence':
      let condition = {
        content: {
          [Op.like]: `%${keyword}%`,
        }
      };
      count = await models.sentence_model.count({where: condition});
      maxPage = Math.ceil(count / ps)
      data = await models.sentence_model.findAll({
          raw: true,
          where: condition,
          limit: ps,
          offset: (pn - 1) * ps,
          attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect'],
      });
      data = data.map(item => {
        return {
          ...item,
          tag: eval(`(${item.tag})`)
        }
      })
      break;
    case 'special':
      count = await models.special_model.count({where: {
        title: {
          [Op.like]: `%${keyword}%`,
        }
      }});
      maxPage = Math.ceil(count / ps)
      data = await models.special_model.findAll({
          raw: true,
          where: {
            title: {
              [Op.like]: `%${keyword}%`,
            }
          },
          limit: ps,
          offset: (pn - 1) * ps,
          attributes: ['sid', 'title', 'categoryId'],
      });
      break;
    case 'tag':
      let tagSentence = await models.tag_model.findAll({
        raw: true,
        where: {
          name: {
            [Op.like]: `%${keyword}%`,
          }
        },
        attributes: ['sentence']
      })
      let filterSentenceId = [];
      tagSentence = tagSentence || [];
      tagSentence.forEach(item => {
        let sentenceGroup = eval(`(${item.sentence})`) || [];
        filterSentenceId = filterSentenceId.concat(sentenceGroup);
      });
      filterSentenceId = Array.from(new Set(filterSentenceId));
      count = filterSentenceId.length;
      maxPage = Math.ceil(count / ps)
      data = await models.sentence_model.findAll({
          raw: true,
          where: {
            id: {
              [Op.in]: filterSentenceId,
            }
          },
          limit: ps,
          offset: (pn - 1) * ps,
          attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect'],
      });
      data = data.map(item => {
        return {
          ...item,
          tag: eval(`(${item.tag})`)
        }
      })
      break;
    default:
      data = [];
  }
  ctx.body = {
    ...resBody.success,
    type,
    data,
    count,
    maxPage
  };
});
// 点赞
router.post('/thumbsUp', async(ctx) => {
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  let { typeId, type, status } = ctx.request.body;
  if (typeId === '' ||
   ![1, 2].includes(type) ||
   ![0, 1].includes(status)
  ) {
    throw({
      ...resBody.paramError
    })
  }
  switch (type) {
    // 句子点赞
    case 1:
      if (status === 1) {
        // 点赞
        await sequelize.transaction(async t => {
          await models.zan_model.create({
            type_id: typeId,
            type: type,
            user_id: userInfo.users_id,
            status: status,
            create_time: new Date
          }, {
              transaction: t,
              fields: ['type_id', 'type', 'user_id', 'status', 'create_time']
            }
          );
        });
        // 提交句子点赞数据
        await models.sentence_model.increment('like', {
          by: 1,
          where: {
            id: typeId
          }
        });
      } else {
        // 取消点赞
        await models.zan_model.destroy({
          where: {
            type_id: typeId,
            type: type,
            user_id: userInfo.users_id
          }
        });
        // 取消赞
        await models.sentence_model.decrement('like', {
          by: 1,
          where: {
            id: typeId
          }
        });
      }
      break;
    // 评论点赞
    case 2:
      if (status === 1) {
        // 点赞
        await sequelize.transaction(async t => {
          await models.zan_model.create({
            type_id: typeId,
            type: type,
            user_id: userInfo.users_id,
            status: status,
            create_time: new Date
          }, {
              transaction: t,
              fields: ['type_id', 'type', 'user_id', 'status', 'create_time']
            }
          );
        });
        // 提交评论点赞数据
        await models.comment_model.increment('praise', {
          by: 1,
          where: {
            id: typeId
          }
        });
      } else {
        // 取消点赞
        await models.zan_model.destroy({
          where: {
            type_id: typeId,
            type: type,
            user_id: userInfo.users_id
          }
        });
        // 取消赞
        await models.comment_model.decrement('praise', {
          by: 1,
          where: {
            id: typeId
          }
        });
      }
      break;
    default:
      break;
  }
  let thumbsUp = await thumbsUpList(ctx);
  ctx.body = { 
    ...resBody.success,
    data: thumbsUp
  };
})

// 收藏
router.post('/collect', async(ctx) => {
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  let { sentenceId, status } = ctx.request.body;
  if (sentenceId === '' ||
   ![0, 1].includes(status)
  ) {
    throw({
      ...resBody.paramError
    })
  }
  if (status === 1) {
    // 收藏
    await sequelize.transaction(async t => {
      await models.collect_model.create({
        sentence_id: sentenceId,
        user_id: userInfo.users_id,
        status: status,
        create_time: new Date
      }, {
          transaction: t,
          fields: ['sentence_id', 'type', 'user_id', 'status', 'create_time']
        }
      );
    });
    // 提交句子点赞数据
    await models.sentence_model.increment('collect', {
      by: 1,
      where: {
        id: sentenceId
      }
    });
  } else {
    // 取消收藏
    await models.collect_model.destroy({
      where: {
        sentence_id: sentenceId,
        user_id: userInfo.users_id
      }
    });
    await models.sentence_model.decrement('collect', {
      by: 1,
      where: {
        id: sentenceId
      }
    });
  }
  let collect = await collectList(ctx);
  ctx.body = { 
    ...resBody.success,
    data: collect
  };
})
// 评论提交 commont
router.post('/commont', async(ctx) => {
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  let { sentenceId, comment } = ctx.request.body;
  if (!sentenceId || !comment ) {
    throw({
      ...resBody.paramError
    })
  }
  // compose_type 1句子 2文章
  await sequelize.transaction(async t => {
    await models.comment_model.create({
      compose_id: sentenceId,
      compose_type: 1,
      content: comment,
      praise: 0,
      from_userid: userInfo.users_id,
      create_time: new Date
    }, {
        transaction: t,
        fields: ['compose_id', 'compose_type', 'content', 'praise', 'from_userid', 'create_time']
      }
    );
  });
  let commentList = await getCommentList(sentenceId);
  // count 个数
  // rows 数据
  ctx.body = {
    ...resBody.success,
    data: commentList.rows || [],
    count: commentList.count || 0
  }
});
// 拉取评论
router.post('/getCommont', async(ctx) => {
  // type: 1.句子 2.文章
  let { type, id } = ctx.request.body;
  let commentList = {}; 
  if (type === 1) {
    commentList = await getCommentList(id);
  }
  ctx.body = {
    ...resBody.success,
    data: commentList.rows || [],
    count: commentList.count || 0
  }
})
// 回复评论
router.post('/setReplyCommont', async(ctx) => {
  // type: 1.句子 2.文章
  let { compose_id, compose_type, comment_id, content, to_uid } = ctx.request.body;
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  if (!compose_id || !compose_type || !comment_id || !content || !to_uid) {
    throw({
      ...resBody.paramError
    })
  }
  await sequelize.transaction(async t => {
    await models.reply_model.create({
      compose_id: compose_id,
      compose_type: compose_type,
      comment_id: comment_id,
      content: content,
      praise: 0,
      form_uid: userInfo.users_id,
      to_uid: to_uid,
      create_time: new Date
    }, {
        transaction: t,
        fields: ['compose_id', 'compose_type', 'comment_id', 'content', 'praise', 'form_uid', 'to_uid', 'create_time']
      }
    );
  });
  ctx.body = {
    ...resBody.success
  }
})
// 我的收藏
router.post('/getCollectList', async(ctx) => {
  let { 
    pn = 1,
    ps = 20 
  } = ctx.request.body;
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  let data = await models.collect_model.findAll({
    where: {
      user_id: userInfo.users_id
    },
    order: [['id', 'DESC']],
    limit: ps,
    offset: (pn - 1) * ps,
    attributes: ['id', 'sentence_id', 'status', 'create_time'],
    include: [
      {
        model: models.sentence_model,
        as: 'sentence',
        attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect']
      }
    ]
  });
  let count = await models.collect_model.count({
    where: {
      user_id: userInfo.users_id
    }
  });
  ctx.body = {
    ...resBody.success,
    data: {
      data,
      count,
      totalPage: Math.ceil(count / ps)
    }
  }
})
// 我的点赞
router.post('/getPraiseList', async(ctx) => {
  let { 
    pn = 1,
    ps = 20 
  } = ctx.request.body;
  let userInfo = loginState(ctx);
  if (!userInfo.users_id) {
    throw({
      ...resBody.userNotLogin
    })
  }
  let data = await models.zan_model.findAll({
    where: {
      user_id: userInfo.users_id,
      type: 1
    },
    order: [['id', 'DESC']],
    limit: ps,
    offset: (pn - 1) * ps,
    attributes: ['id', 'type_id', 'status', 'create_time'],
    include: [
      {
        model: models.sentence_model,
        as: 'sentence',
        attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect']
      }
    ]
  });
  let count = await models.zan_model.count({
    where: {
      user_id: userInfo.users_id,
      type: 1
    }
  });
  ctx.body = {
    ...resBody.success,
    data: {
      data,
      count,
      totalPage: Math.ceil(count / ps)
    }
  }
})
module.exports = router